package top.vains.aop;

import io.jsonwebtoken.Claims;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.vains.entity.Files;
import top.vains.util.JwtUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 上传切面
 *
 * @author vains
 * @version 1.0
 * @since 2020/3/10 15:45
 **/
@Aspect
@Component
public class UploadAspect {

    /**
     * 定义切入点，切入点为上传方法
     *通过@Pointcut注解声明频繁使用的切点表达式
     */
    @Pointcut("execution(public * top.vains.controller.FilesController.upload(..)))")
    public void brokerAspect(){
        // 不需要任何代码，因为这里是切点
    }

    @Before("brokerAspect()")
    public void beforeUpload(JoinPoint joinPoint) {
        //这个RequestContextHolder是SpringMvc提供来获得请求的东西
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
            String token = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(token)) {
                Claims claims = JwtUtils.parseJwt(token);
                Integer userId = (Integer) claims.get("userId");
                Object[] args = joinPoint.getArgs();
                for (Object arg : args) {
                   if (arg instanceof Files) {
                       ((Files)arg).setUserId(userId);
                   }
                }
            }
        }
    }

}
